package com.epoint.androidphone.mobileoa.ui.mail;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.epoint.androidmobile.core.control.AlertUtil;
import com.epoint.androidmobile.core.control.ToastUtil;
import com.epoint.androidmobile.core.string.StringHelp;
import com.epoint.androidphone.R;
import com.epoint.androidphone.mobileoa.service.mqtt.MQTTUtil;
import com.epoint.androidphone.mobileoa.ui.contacts.ContactsListView;
import com.epoint.androidphone.mobileoa.ui.filechoose.FileChooseView;
import com.epoint.androidphone.mobileoa.ui.superview.SuperPhonePage;
import com.epoint.androidmobile.bizlogic.dbservice.ConfigKey;
import com.epoint.androidmobile.bizlogic.mail.task.MailSendTask;
import com.epoint.androidmobile.bizlogic.mail.model.SendAttachModel;
/**
 * @author liyc
 * @time 2013-5-7 上午10:08:24
 * @annomation 邮件发送
 */
public class MailSendView extends SuperPhonePage {

	EditText etSjr,etCsr,etMailTitle,etMailContent;
	ImageView ivSjrClear,ivCsrClear;
	Button btSend;
	ImageButton ibAttach;
	List<SendAttachModel> attachList = new ArrayList<SendAttachModel>();
	ListView lvAttach;
	AttachListAdapter adapter = new AttachListAdapter();

	long MailSendTaskID;

	int EnterFlag;//2回复,3转发

	LinearLayout llAttach;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addContentViewAndTitle(R.layout.mailsend, getIntentViewTitle());
		etSjr = (EditText) findViewById(R.id.etSjr);
		etCsr = (EditText) findViewById(R.id.etCsr);
		etMailTitle = (EditText) findViewById(R.id.etMailTitle);
		etMailContent = (EditText) findViewById(R.id.etMailContent);
		ivSjrClear = (ImageView) findViewById(R.id.ivSjrClear);
		ivCsrClear = (ImageView) findViewById(R.id.ivCsrClear);
		ivCsrClear.setOnClickListener(this);
		ivSjrClear.setOnClickListener(this);
		etSjr.setOnClickListener(this);
		etCsr.setOnClickListener(this);
		btSend = (Button) findViewById(R.id.btSend);
		llAttach = (LinearLayout) findViewById(R.id.llAttach);
		//		ibAttach = (ImageButton) findViewById(R.id.ibAttach);
		//		ibAttach.setOnClickListener(this);
		btSend.setOnClickListener(this);

		//		lvAttach = (ListView) findViewById(R.id.lvAttach);
		//		lvAttach.setOnItemLongClickListener(this);
		//		lvAttach.setAdapter(adapter);
		etCsr.setTag("");
		getIvRight().setBackgroundResource(R.drawable.btn_attach_selector);
		getIvRight().setVisibility(View.VISIBLE);
		EnterFlag = getIntent().getIntExtra("EnterFlag", 0);
		if(EnterFlag==2)
		{
			getTvTitle().setText("邮件回复");
			String HFTitle = getIntent().getStringExtra("MailTitle");
			String ToUserDispNameList = getIntent().getStringExtra("ToUserDispNameList");
			String ToUserGuidList = getIntent().getStringExtra("ToUserGuidList");
			etSjr.setText(ToUserDispNameList);
			etSjr.setTag(ToUserGuidList);
			etMailTitle.setText("回复:"+HFTitle);
		}
		else if(EnterFlag==3)
		{
			getTvTitle().setText("邮件转发");
			String ZFTitle = getIntent().getStringExtra("MailTitle");
			etMailTitle.setText("转发:"+ZFTitle);
			int zfAttachNums = getIntent().getIntExtra("ZFAttachSize",0);
			if(zfAttachNums>0)
			{
				String[] filenames = getIntent().getStringArrayExtra("filenames");
				String[] fileguids = getIntent().getStringArrayExtra("fileguids");
				for(int i=0;i<zfAttachNums;i++)
				{
					SendAttachModel s = new SendAttachModel();
					s.fileguid = fileguids[i];
					s.filename = filenames[i];
					s.type = 2;
					s.path = "";
					attachList.add(s);
				}
				refAttachButton();
			}

		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		if(arg0==lvAttach)
		{
			final int mp = arg2;
			AlertUtil.showAlertMenu(this, "附件操作", new String[]{"移除"}, new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					attachList.remove(mp);
					adapter.notifyDataSetChanged();
				}
			});
		}
		return super.onItemLongClick(arg0, arg1, arg2, arg3);
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		if(v==etSjr||v==etCsr)
		{
			Intent intent = new Intent(this, ContactsListView.class);
			intent.putExtra("enterflag", 2);
			intent.putExtra("EnterClassName", this.getClass().getName());
			startActivityForResult(intent, v==etSjr?1001:1002);
		}
		else if(v==btSend)
		{
			if(etSjr.getText().toString().trim().length()==0)
			{
				ToastUtil.toastWorning(this, "请添加收件人");
				return;
			}

			showDialogMiddle("正在发送邮件...");
			HashMap<String, Object> param = getPassMap();
			param.put("Subject", etMailTitle.getText().toString());
			param.put("ToUserGuidList", etSjr.getTag().toString());
			param.put("SecretUserGuidList", "");
			param.put("ChaoSongUserGuidList", etCsr.getTag().toString());
			param.put("MailContent", etMailContent.getText().toString());
			param.put("ATTACHList", attachList);

			if(EnterFlag==2||EnterFlag==3){
				String mailsendinfo = "<b>发件人：</b>"
						+ getIntent().getStringExtra("FROMDISPNAME")
						+ "<br><br>";
				mailsendinfo += "<b>发件时间：</b>"
						+ getIntent().getStringExtra("SENDTIME")
						+ "<br><br>";
				mailsendinfo += "<b>主题：</b>"
						+ getIntent().getStringExtra("MailTitle")
						+ "<br><br>";// replaytitle
				String yuanMailContent = getIntent().getStringExtra(
						"MailContent");
				String lastC = etMailContent.getText().toString()
						+ "<br><br><hr><br><br>" + mailsendinfo
						+ yuanMailContent;

				param.put("MailContent", lastC);
			}

			MailSendTaskID = new MailSendTask(this,param).startTask();


		}
		else if(v==getIvRight())
		{
			Intent intent = new Intent(this, FileChooseView.class);
			intent.putExtra("EnterClassName", this.getClass().getName());
			startActivityForResult(intent, 1003);
		}
		else if(v==ivCsrClear)
		{
			etCsr.setText("");
			etCsr.setTag("");
		}
		else if(v==ivSjrClear)
		{
			etSjr.setText("");
			etSjr.setTag("");
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==1001){
			switch (resultCode) {
			case RESULT_OK:
				etSjr.setText(data.getStringExtra("names"));
				etSjr.setTag(data.getStringExtra("guids"));
				break;
			default:
				break;
			}
		}
		else if(requestCode==1002)
		{
			switch (resultCode) {
			case RESULT_OK:
				etCsr.setText(data.getStringExtra("names"));
				etCsr.setTag(data.getStringExtra("guids"));
				break;
			default:
				break;
			}
		}
		else if(requestCode==1003)
		{
			switch (resultCode) {
			case RESULT_OK:
				String path = data.getStringExtra("path");
				File f = new File(path);
				SendAttachModel s = new SendAttachModel();
				s.filename = f.getName();
				s.type = 1;
				s.fileguid = "";
				s.path = path;

				boolean isExist = false;
				for(SendAttachModel sm:attachList)
				{
					if(sm.path.equals(s.path))
					{
						isExist = true;
					}
				}

				if(isExist){
					ToastUtil.toastWorning(this, "该附件已添加");
				}
				else{
					attachList.add(s);
					refAttachButton();


					//					adapter.notifyDataSetChanged();
				}
				break;
			default:
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	void refAttachButton()
	{
		llAttach.removeAllViews();
		for(int i=0;i<attachList.size();i++)
		{
			final int mi = i;
			TextView btn = new TextView(this);
			Drawable d = getResources().getDrawable(R.drawable.btn_attach2);
			d.setBounds(0, 0, d.getMinimumWidth(), d.getMinimumHeight());
			btn.setCompoundDrawables(d, null, null, null);
			btn.setText(attachList.get(i).filename);
			btn.setGravity(Gravity.CENTER_VERTICAL);
			btn.setBackgroundResource(R.drawable.text_item_selector);
			btn.setClickable(true);
			btn.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {
					AlertUtil.showAlertMenu(getContext(), "附件操作", new String[]{"移除"}, new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							attachList.remove(mi);
							adapter.notifyDataSetChanged();
						}
					});
					return false;
				}
			});
			llAttach.addView(btn);
		}
	}

	@Override
	public void refreshUI(long taskId, Object obj) {
		super.refreshUI(taskId, obj);
		if(taskId==MailSendTaskID)
		{
			if(validateXML(obj))
			{
				ToastUtil.toastShort(this, "邮件发送成功");
				finish();

				if(getString(R.string.message_push_enable).equals("1")){
					new Thread(
							new Runnable() {

								@Override
								public void run() {
									String[] guids = etSjr.getTag().toString().split(";");
									for(int i=0;i<guids.length;i++)
									{
										String topicStr = "NewMail/"+guids[i];
										MQTTUtil.p1(getContext(), topicStr, etMailTitle.getText().toString());
									}

								}
							}).start();

				}
			}
		}
	}

	class AttachListAdapter extends BaseAdapter
	{

		@Override
		public int getCount() {
			return attachList.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			LayoutInflater mInflater = LayoutInflater.from(getContext());
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.listviewfile, null);
				holder.ivIcon = (ImageView) convertView
						.findViewById(R.id.fc_img);
				holder.tvName = (TextView) convertView.findViewById(R.id.fc_title);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			SendAttachModel s = attachList.get(position);
			holder.tvName.setText(s.filename);
			holder.ivIcon.setBackgroundResource(R.drawable.btn_attach1);
			return convertView;
		}

	}

	class ViewHolder
	{
		ImageView ivIcon;
		TextView tvName;
	}
}
